from garetjax import config
import flickrapi
from django.http import HttpResponseRedirect

def require_flickr_auth(view):
    """
    View decorator, redirects users to Flickr when no valid
    authentication token is available.
    """

    import logging
    logging.basicConfig()
    log = logging.getLogger(__name__)
    log.setLevel(logging.DEBUG)

    def protected_view(request, *args, **kwargs):
        token = config.get('flickr:token', False)
        
        if token:
            log.info('Getting token from config: %s' % token)
        else:
            token = None
            log.info('No token in database')

        f = flickrapi.FlickrAPI(config.get('flickr:api_key'),
               config.get('flickr:api_secret'), token=token)

        if token is not None:
            # We have a token, but it might not be valid
            log.info('Verifying token')
            try:
                f.auth_checkToken()
            except flickrapi.FlickrError:
                token = None
                config.delete('flickr:token')

        if not token:
            # No valid token, so redirect to Flickr
            log.info('Redirecting user to Flickr to get frob')
            url = f.web_login_url(perms='read')
            return HttpResponseRedirect(url)

        # If the token is valid, we can call the decorated view.
        log.info('Token is valid')

        return view(request, *args, **kwargs)

    return protected_view